package com.hdl.m3u8;


import androidx.annotation.Nullable;

import com.cxy.common.request.ApiService;
import com.fy.baselibrary.application.ioc.ConfigUtils;
import com.fy.baselibrary.retrofit.RequestUtils;
import com.fy.baselibrary.retrofit.RxHelper;
import com.fy.baselibrary.retrofit.converter.file.FileResponseBodyConverter;
import com.fy.baselibrary.retrofit.load.LoadOnSubscribe;
import com.fy.baselibrary.retrofit.load.LoadService;
import com.fy.baselibrary.retrofit.load.down.DownLoadListener;
import com.fy.baselibrary.retrofit.observer.FileCallBack;
import com.fy.baselibrary.retrofit.observer.IProgressDialog;
import com.fy.baselibrary.utils.Constant;
import com.fy.baselibrary.utils.FileUtils;
import com.fy.baselibrary.utils.cache.SpfAgent;
import com.fy.baselibrary.utils.notify.L;
import com.hdl.m3u8.bean.M3U8;
import com.hdl.m3u8.bean.M3U8Item;
import com.hdl.m3u8.utils.MUtils;

import java.io.File;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

/**
 * description </p>
 * Created by fangs on 2021/3/8 14:52.
 */
public class DownUtils {

    //将Url转换为M3U8对象
    public static void downLoadM3u8(String url, @Nullable IProgressDialog pDialog, DownLoadListener<File> loadListener){
        RequestUtils.create(ApiService.class)
                .downloadM3u8(url)
                .map(new Function<ResponseBody, M3U8>() {
                    @Override
                    public M3U8 apply(@NonNull ResponseBody responseBody) throws Exception {
                        return MUtils.parseIndex(url, responseBody.byteStream());
                    }
                })
                .flatMap(new Function<M3U8, ObservableSource<M3U8Item>>() {
                    @Override
                    public ObservableSource<M3U8Item> apply(@NonNull M3U8 m3U8) throws Exception {
                        return Observable.fromIterable(m3U8.getTsList());
                    }
                })
                .flatMap(new Function<M3U8Item, ObservableSource<?>>() {
                    @Override
                    public ObservableSource<?> apply(@NonNull M3U8Item m3U8Ts) throws Exception {
                        String urlPath;
                        if ("http".equals(m3U8Ts.getFile().substring(0, 4))) {
                            urlPath = m3U8Ts.getFile();
                        } else {
                            urlPath = m3U8Ts.getBasePath() + m3U8Ts.getFile();
                        }

                        return downLoadFile(urlPath);
                    }
                })
                .subscribeOn(Schedulers.io())
                .subscribe(new FileCallBack(url, pDialog) {
                    @Override
                    protected void downSuccess(File file) {
                        loadListener.onProgress("100");
                        RequestUtils.runUiThread(() -> {
                            loadListener.onSuccess((File) file);//已在主线程中，可以更新UI
                        });
                    }

                    @Override
                    protected void downProgress(String percent) {
                        loadListener.onProgress(percent);
                    }
                });
    }

    public static Observable<Object> downLoadFile(final String url){
        final String filePath = FileUtils.folderIsExists(FileUtils.DOWN, ConfigUtils.getType()).getPath();
        final File tempFile = FileUtils.getTempFile(url, filePath);

        return Observable.just(url)
                .map(new Function<String, String>() {
                    @Override
                    public String apply(String downUrl) throws Exception {

                        File targetFile = FileUtils.getFile(downUrl, filePath);
                        if (targetFile.exists()) {
                            SpfAgent.init("").saveInt(tempFile.getName() + Constant.FileDownStatus, 4).commit(false);//下载完成
                            return targetFile.getPath();
                        } else {
                            return "bytes=" + tempFile.length() + "-";
                        }
                    }
                })
                .flatMap(new Function<String, ObservableSource<Object>>() {
                    @Override
                    public ObservableSource<Object> apply(String downParam) throws Exception {
                        L.e("fy_file_FileDownInterceptor", "文件下载开始---" + Thread.currentThread().getName());
                        if (downParam.startsWith("bytes=")) {
//                            return RequestUtils.create(LoadService.class).download(downParam, url);
                            LoadOnSubscribe loadOnSubscribe = new LoadOnSubscribe();
                            FileResponseBodyConverter.addListener(url, loadOnSubscribe);
                            return Observable.merge(Observable.create(loadOnSubscribe), RequestUtils.create(LoadService.class).download(downParam, url));
                        } else {
                            SpfAgent.init("").saveInt(tempFile.getName() + Constant.FileDownStatus, 4).commit(false);
                            return Observable.just(new File(downParam));
                        }
                    }
                });
    }

}
